package middleware

import (
	"fmt"
	"log"
	"os"
	"strconv"

	"github.com/jmoiron/sqlx"
	_ "github.com/lib/pq"
)

const (
	dbname           = "postgres"
	postgresHost     = "POSTGRES_HOST"
	postgresPort     = "POSTGRES_PORT"
	postgresUser     = "POSTGRES_USERNAME"
	postgresPassword = "POSTGRES_PASSWORD"
)

type Postgresql struct {
	db *sqlx.DB
}

func NewPostgresClient() Postgresql {
	port, err := strconv.Atoi(os.Getenv(postgresPort))
	if err != nil {
		log.Printf("Postgresql port is not numeric: '%s'", os.Getenv(postgresPort))
		panic(err)
	}

	psqlInfo := fmt.Sprintf("host=%s port=%d user=%s "+
		"password=%s dbname=%s sslmode=disable",
		os.Getenv(postgresHost), port, os.Getenv(postgresUser), os.Getenv(postgresPassword), "postgres")
	log.Print(psqlInfo)

	db, err := sqlx.Open("postgres", psqlInfo)
	if err != nil {
		log.Printf("Failed to connect to postgres")
		panic(err)
	}

	log.Printf("Start Postgres Client, address: %s:%d\n", os.Getenv(postgresHost), port)

	db.SetMaxOpenConns(20)
	db.SetMaxIdleConns(10)
	return Postgresql{db: db}
}

func (c Postgresql) Visit() {
	var result []KeyValue
	// Execute the query
	err := c.db.Select(&result, "SELECT * FROM dummy")
	if err != nil {
		log.Printf("Fail to query postgres: %v", err)
		return
	}
	log.Printf("Query postgres: %v", result)
}

func (c Postgresql) Close() {
	_ = c.db.Close()
}
